package cn.wolfcode.crm.shiro;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.mapper.PermissionMapper;
import cn.wolfcode.crm.mapper.RoleMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;


@Component("crmRealm")
public class CRMRealm extends AuthorizingRealm {
    //在set方法注入密码匹配器
    @Autowired
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        super.setCredentialsMatcher(credentialsMatcher);
    }
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取当前登录用户
        Subject subject = SecurityUtils.getSubject();
        Employee employee = (Employee)subject.getPrincipal();
        //是超管的话,给他添加一个admin角色(方便后面判断是否是超管),给所有权限
        if(employee.isAdmin()){
            info.addRole("admin");
            info.addStringPermission("*:*");
        }
        //若不是超管需要去数据库查有哪些角色和权限
        //拿角色的sn
        List<String> roles = roleMapper.selectByEmployeeId(employee.getId());
        info.addRoles(roles);
        //拿权限的表达式
        List<String> permissions = employeeMapper.selectByEmployeeId(employee.getId());
        info.addStringPermissions(permissions);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取登录的用户名(令牌中的,用户登录的)
        String principal = (String)token.getPrincipal();
        Employee employee = employeeMapper.selectByName(principal);
        if(employee != null){
            //因为加密是md5和盐,我们使用带盐的构造器,利用shiro提供的工具类转化格式(ByteSource.Util.bytes())
            return new SimpleAuthenticationInfo(employee,employee.getPassword(),
                    ByteSource.Util.bytes(employee.getName()),"crmRealm");
        }
        return null;
    }
}
